import { createRouter, createWebHashHistory } from 'vue-router';
import nprogress from 'nprogress';
import staticRouter from './modules/static-router';
import errorRouter from './modules/error-router';
import dynamicRoute from "@/router/modules/dynamic-router";

nprogress.configure({
	showSpinner: true
});

const creater = () => {
	return createRouter({
		history: createWebHashHistory(),
		routes: [...staticRouter, ...errorRouter],
		strict: false,
		scrollBehavior: (_to, _from, position) => {
			return position ?? { top: 0, left: 0 };
		}
	});
};

const router = creater();

// 设置标题
const setTitle = (to: any, _from: any) => {
	const title = import.meta.env.VITE_GLOB_APP_TITLE;
	document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;
};

/**
 * 验证
 */
const vaild = (to: any, _from: any, next: any): Boolean => {
	var store = useStore();
	if (to.path !== store.config.urls.login) {
		if (store.user.token === '') {
			next({ name: 'login', query: { redirect: to.path } });
			return false;
		}
	}
	return true;
};

/**
 * 动态加载菜单
 */
const loadRoutes = async () => {
	var routerStore = useRouterStore();
	if (routerStore.routers.length === 0) {
		await dynamicRoute();
	}
};

const startNext = (to: any, from: any, next: any) => {
	if (to.matched.length === 0) {
		const url = window.location.href.split('#')[1];
		next({ path: url });
	} else {
		next();
	}
};

router.beforeEach(async (to, from, next) => {
	nprogress.start();
	if (vaild(to, from, next)) {
		loadRoutes();
		setTitle(to, from);
		startNext(to, from, next);
	}
});
router.afterEach((to, from, failure) => {
	nprogress.done();
})

router.onError((error) => {
	
});

export const resetRouter = () => { };

export default router;
